package com.mmall.service;

import com.google.common.collect.Lists;
import com.mmall.common.RequestHolder;
import com.mmall.dao.SysRoleUserMapper;
import com.mmall.dao.SysUserMapper;
import com.mmall.model.SysRoleUser;
import com.mmall.model.SysUser;
import com.mmall.util.IpUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class SysRoleUserService {

    @Resource
    private SysRoleUserMapper mapper;
    @Resource
    private SysUserMapper userMapper;
    @Resource
    private SysLogService sysLogService;

    public void changeRoleUsers(int roleId, List<Integer> userIdList) {
        //取出之前存在的
       List<Integer> originUserList = mapper.getUserIdListByRoleId(roleId);

       if (originUserList.size() == userIdList.size()){
           Set<Integer> originUserSet = new HashSet<>(originUserList);
           originUserSet.removeAll(userIdList);
           if (CollectionUtils.isEmpty(originUserSet)){
               return;
           }
       }
       updateRoleUsers(roleId,userIdList);

       sysLogService.saveUserRoleLog(roleId,originUserList,userIdList);

    }

    @Transactional
    public void updateRoleUsers(int roleId, List<Integer> userIdList) {
        mapper.deleteByRoleId(roleId);
        if (CollectionUtils.isEmpty(userIdList)){
            return;
        }
        List<SysRoleUser> roleUsers = Lists.newArrayList();
        for (Integer userId : userIdList){
            SysRoleUser sysRoleUser = SysRoleUser.builder()
                    .roleId(roleId)
                    .userId(userId)
                    .operateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()))
                    .operateTime(new Date())
                    .operator(RequestHolder.getCurrentUser().getUsername())
                    .build();
            roleUsers.add(sysRoleUser);
        }
        mapper.batchInsert(roleUsers);
    }

    /**
     * 获取已选的用户列表
     * @param roleId
     * @return
     */
    public List<SysUser> getListByRoleId(int roleId) {
       List<Integer> userIds = mapper.getUserIdListByRoleId(roleId);
       if (CollectionUtils.isEmpty(userIds)){
           return Lists.newArrayList();
       }
       return userMapper.getByIdList(userIds);
    }
}
